<script setup>
import {
  ref,
  reactive,
  computed,
  watch,
  nextTick,
  onMounted,
  onBeforeUnmount,
} from "vue";
import request from "@/common/utils/request";
import { nanoid } from "nanoid";
import { PlayCircleOutlined, PauseCircleOutlined } from "@ant-design/icons-vue";
import { useStore } from "vuex";
import { Empty } from "ant-design-vue";
import AudioPlayer from "../../../../components/AudioPlayer/index.vue";

const emit = defineEmits(["selectVoice"]);
const props = defineProps({
  audioId: {
    type: [Number, String],
    default: "",
  },
});


const store = useStore();
const state = reactive({
  activeKey: "1",
  // 场景列表(类型)
  category: [],
  // 音色列表
  list: [],
  // 语气列表
  toneList: [],
  // 情感类型
  emotion_intensity: "",
  // 选择的音频
  selectVoice: null,

  audioPlayer: null,
});

const formState = reactive({
  speed: 0,
  volume: 100,
  emotion_intensity: 50,
});

// 默认音频配置
const voice_config = computed(() => {
  return store.state.videoMixCut.voice_config;
});

onMounted(() => {
  initData();
});

// 初始化获取
const initData = async () => {
  await store.dispatch("videoMixCut/getDefaultVoiceData");
  getVoiceData();
};
// 获取场景数据
const getVoiceData = async () => {
  const res = await request.get("/work_ai", "/user/shotstack/voice/category");
  state.category = res.result;
  // 场景类型初始赋值
  state.activeKey = res.result[0].key;
  console.log(res, "场景列表");
  getVoiceList();
};

// 获取音色列表
const getVoiceList = async () => {
  const res = await request.get("/work_ai", "/user/shotstack/voice/list", {
    category: state.activeKey,
  });
  if (res.result.length > 0) {
    console.log(res, "音色列表");
    res.result.forEach((element) => {
      // 给场景下面的分类赋值id
      element.id = nanoid();
    });
    state.list = res.result;
    console.log(state.list, "音频列表");
    // 获取语气列表
    state.toneList = res.result[0].item[0]?.emotion_style || [];
    // 获取情感类型
    state.emotion_category = state.toneList?.[0]?.key || "neutral";
  } else {
    state.list = [];
  }
};

// 选择某项音频
const selectItem = (data) => {
  state.selectVoice = data;
  emit("selectVoice", data);
};

const playCircleOutlined = (data, type) => {
  if (data.isPlay) {
    data.isPlay = false;
  } else {
    data.isPlay = true;
  }
  if (type == "pauseCircle") {
    if (state.audioPlayer) {
      state.audioPlayer.pause(); // 暂停当前播放的音频
      state.audioPlayer.src = "";
    }
    state.audioPlayer = new Audio(data.voice_url); // 播放下一个音频文件
    state.audioPlayer.play(); // 开始播放音频
  } else {
    console.log("暂停");
    state.audioPlayer.src = "";
    state.audioPlayer.pause();
  }
  state.list.forEach((voice) => {
    if (voice.item) {
      voice.item.forEach((item) => {
        if (item.id !== data.id) {
          item.isPlay = false;
        }
      });
    }
  });
  if (state.audioPlayer) {
    state.audioPlayer.addEventListener("ended", function () {
      // 这里写入结束回调函数的代码
      console.log("结束语音");
      state.list.forEach((voice) => {
        if (voice.item) {
          voice.item.forEach((item) => {
            if (item.id == data.id) {
              item.isPlay = false;
            }
          });
        }
      });
    });
  }
};

const tabsChange = (data) => {
  console.log(data, "tabchange");
  getVoiceList();
};
// 页面卸载
onBeforeUnmount(() => {
  if (state.audioPlayer) {
    state.audioPlayer.pause();
    state.audioPlayer = null;
  }
});
</script>

<template>
  <div class="voiceList">
    <a-tabs v-model:activeKey="state.activeKey" @change="tabsChange">
      <a-tab-pane
        v-for="item in state.category"
        :key="item.key"
        :tab="item.value"
      >
        <div class="is_content">
          <!-- 每一项的分组 -->
          <template v-if="state.list.length">
            <div class="voiceList_item" v-for="ele in state.list" :key="ele.id">
              <h2>{{ ele.gender_title }}</h2>
              <div class="cart_box">
                <!-- 每个分组下面的卡片列表 -->
                <div
                  class="cart_item"
                  :class="{
                    active:
                      state.selectVoice && state.selectVoice.id == cart.id,
                  }"
                  @click="selectItem(cart)"
                  v-for="cart in ele.item"
                  :key="cart.id"
                >
                  <div class="cart_item_left">
                    <PlayCircleOutlined
                      v-if="cart.isPlay"
                      @click.stop="playCircleOutlined(cart, 'playCircle')"
                    ></PlayCircleOutlined>
                    <PauseCircleOutlined
                      v-else
                      @click.stop="playCircleOutlined(cart, 'pauseCircle')"
                    ></PauseCircleOutlined>
                  </div>
                  <div class="cart_item_right">
                    <span>{{ cart.name }}</span>
                    <span class="human_style">{{ cart.human_style }}</span>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <template v-else>
            <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" />
          </template>
        </div>
      </a-tab-pane>
    </a-tabs>

    <div class="controls">
      <div class="config_cart">
        <span>语速 </span>
        <div class="slider_box">
          <a-slider
            class="slider"
            :min="voice_config?.speed?.min"
            :max="voice_config?.speed?.max"
            id="test"
            :step="voice_config?.speed?.separate"
            v-model:value="formState.speed"
          />
        </div>
      </div>
      <div class="config_cart">
        <span>音量</span>
        <div class="slider_box">
          <a-slider
            class="slider"
            :min="voice_config?.volume?.min"
            :max="voice_config?.volume?.max"
            id="test"
            :step="voice_config?.volume?.separate"
            v-model:value="formState.volume"
          />
        </div>
      </div>
      <div class="config_cart">
        <span>情感 </span>
        <div class="slider_box">
          <a-slider
            class="slider"
            :min="voice_config?.intensity?.min"
            :max="voice_config?.intensity?.max"
            id="test"
            :step="voice_config?.intensity?.separate"
            v-model:value="formState.emotion_intensity"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.voiceList {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  // 控制语速等配置容器
  .controls {
    flex: 1;
    padding: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    // background-color: #b1afaf;
    margin-top: 15px;

    .config_cart {
      width: 100%;
      display: flex;
      align-items: center;
      gap: 10px;

      // span {
      //     width: 55px;
      // }

      .slider_box {
        flex: 1;
      }
    }
  }

  .is_content {
    height: 400px;
    display: flex;
    flex-direction: column;
    gap: 20px;
    overflow-y: auto;
    border: 1px solid #d9d9d9;
    border-radius: 8px;
    padding: 10px;

    &::-webkit-scrollbar {
      width: 8px;
      /* 滚动条的宽度 */
      height: 10px;
      /* 滚动条的高度，垂直滚动条可能用得上 */
      display: none;
    }

    &::-webkit-scrollbar-thumb {
      background: #888;
      /* 滑块的背景颜色 */
      border-radius: 10px;
      /* 滑块的圆角 */
    }

    .voiceList_item {
      display: flex;
      flex-direction: column;
      gap: 10px;

      h2 {
        font-size: 16px;
        font-weight: 600;
        margin: 0;
      }

      .cart_box {
        display: flex;
        flex-wrap: wrap;
        // justify-content: last baseline;
        align-content: start;
        gap: 15px;

        .cart_item {
          cursor: pointer;
          display: flex;
          align-items: center;
          // justify-content: space-between;
          padding-left: 10px;
          height: 50px;
          width: 160px;
          border-radius: 8px;
          background-color: #fff;
          border: 1px solid #d1d1d1;
          transition: all 0.3s;

          &:hover {
            border-color: var(--ss-primary-color-hover);
          }

          &.active {
            border-color: var(--ss-primary-color-active);
            // color: #fff;
          }

          .cart_item_left {
            // color: #1decf3;
            font-size: 30px;
            transition: all 0.3s;

            &:hover {
              color: var(--ss-primary-color-hover);
            }
          }

          .cart_item_right {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;

            .human_style {
              color: #666666;
              font-size: 12px;
            }
          }
        }
      }
    }
  }
}
</style>
